package com.xiaobai.DeadLock;

import com.xiaobai.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.TestLiveLock")
public class TestLiveLock {
    /*
    解决活锁的措施就是 执行时间有一定的交错 睡眠时间要不同
     */
    static volatile int count = 10;
    static final Object lock = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            // 期望减到 0 退出循环
            while (count > 0) {
                ThreadUtil.sleep(1);
                count--;
                log.debug("count: {}", count);
            }
        }, "t1").start();
        new Thread(() -> {
            // 期望超过 20 退出循环
            while (count < 20) {
                //随机睡眠时间
                ThreadUtil.sleep(2);
                count++;
                log.debug("count: {}", count);
            }
        }, "t2").start();
    }
}
